//
//  ChangePassword.m
//  Bespoke
//
//  Created by Cheng on 12/10/4.
//
//

#import "ChangePassword.h"
#import "BK_Enviroment.h"
#import "RequestAPIFunction.h"
#import "GDataXMLNode.h"

#define CHANGEPASSWORD_API @"http://54.235.166.43/BeSpokeAPI/ChangePassword.php"

@implementation ChangePassword
@synthesize Tf_NewPassword,Tf_ConfirmPassword,Bt_Cancel,Bt_Done;
@synthesize delegate;

- (IBAction)CancelPressed:(id)sender {
    [delegate CancelPressed_ChangePassword];
}

- (IBAction)DonePressed:(id)sender {
    if ([Tf_NewPassword.text isEqualToString:@""]) {
        UIAlertView *AlertView = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"Please enter Password." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [AlertView show];
        return;
    }
    if (![Tf_ConfirmPassword.text isEqualToString:Tf_NewPassword.text]) {
        UIAlertView *AlertView = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"The two passwords don't match. Try again!" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [AlertView show];
        return;
    }
    
    BK_Enviroment *BK_En_object = [[BK_Enviroment alloc] init];
    
    NSData *responseData =
    [RequestAPIFunction XML_PostRequest:[NSString stringWithFormat:@"<AccountInfo UserName=\"%@\" NewPassword=\"%@\" />",BK_En_object.userName,Tf_ConfirmPassword.text]
                       urlString:CHANGEPASSWORD_API];
    
    //No Network Connection or time out.
    if (responseData == nil)
        return;
    
    NSError *error;
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:responseData options:0 error:&error];
    
    //Check to upload is success.
    if ([[doc nodesForXPath:@"//Success" error:&error] count]!=0) {
        
        [BK_En_object setAuthenticationUserName:BK_En_object.userName Password:Tf_ConfirmPassword.text];
        [delegate CancelPressed_ChangePassword];
    }
}

@end
